package com.heaven.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.heaven.ojcodesandbox.model.ExecuteCodeRequest;
import com.heaven.ojcodesandbox.model.ExecuteCodeResponse;
import com.heaven.ojcodesandbox.model.ExecuteMessage;
import com.heaven.ojcodesandbox.model.JudgeInfo;
import com.heaven.ojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Description TODO
 * @Author HeavenDirt
 * @Date 2024/7/29 20:08
 */
@Slf4j
public abstract class JavaCodeBoxTemplate implements CodeSandbox {
    private final static String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private final static String GLOBAL_JAVA_CLASS_NAME = "Main.java";
/*    private final static String SECURITY_MANAGE_CLASS_NAME = "MySecurityManager";
    private final static String SECURITY_MANAGE_PATH = "F:\\Develop\\oj-code-sandbox\\src\\main\\resources\\security";*/
    private final static long TIME_OUT = 5000L;

    /**
     * 1.保存用户代码到文件
     * @param  code 用户代码
     * @return File
     * @author HeavenDirt
     * @date 2024/7/29 20:17
     */
    public File saveCodeToFile(String code){
        //将用户代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 2.编译代码
     * @param userCodeFile 用户代码文件
     * @return ExecuteMessage
     * @author HeavenDirt
     * @date 2024/7/29 20:22
     */
    public ExecuteMessage compileFile(File userCodeFile){
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if(executeMessage.getExitValue() != 0){
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
            //todo 先抛
            throw new RuntimeException(e);
        }
    }

    /**
     *  3.执行代码
     * @param userCodeFile 用户代码文件
     * @param inputList 输入参数
     * @return List<ExecuteMessage>
     * @author HeavenDirt
     * &#064;date  2024/7/29 20:50
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList){
        //todo 不同
        String userCodeParentPath = userCodeFile.getParent();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx4096m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            //String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main", userCodeParentPath, SECURITY_MANAGE_PATH, SECURITY_MANAGE_CLASS_NAME, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //执行时间限制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("程序超时");
                        if (runProcess.isAlive()) {
                            runProcess.destroyForcibly();
                        } else {
                            runProcess.destroy();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "执行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (IOException e) {
                throw new RuntimeException("程序执行异常",e);
            }
        }
        return executeMessageList;
    }

    /**
     * 4.整理响应结果
     * @param executeMessageList 执行信息列表
     * @return ExecuteCodeResponse
     * @author HeavenDirt
     * @date 2024/7/29 20:40
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值判断是否超时
        long maxTime = 0;
        executeCodeResponse.setStatus(1);
        executeCodeResponse.setMessage("执行成功");
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                //执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);

        return executeCodeResponse;
    }

    /**
     * 5.删除文件
     * @param userCodeFile 用户代码文件
     * @return boolean
     * @author HeavenDirt
     * @date 2024/7/29 20:45
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParent());
            System.out.println("删除文件" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        File userCodeFile = saveCodeToFile(code);
/*        //校验代码
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null) {
            return getErrorResponse(new Exception("代码中包含禁止字符:" + foundWord.getWord()));
        }*/

        //编译代码
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(compileFileExecuteMessage);

        //执行代码
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);

        //4.整理输出
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);

        //5.清理文件
        boolean del = deleteFile(userCodeFile);
        if(!del){
            log.error("delete file error, userCodeFile:{}",userCodeFile.getAbsolutePath());
        }

        return outputResponse;
    }

    //6.错误处理,提升程序健壮性
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        return executeCodeResponse;
    }
}
